/**
 * 下载文件
 * @param { String } filename 文件名
 * @param { Blob } blob 对象
 */
export function download(filename: string, blob: Blob) {
  const url = window.URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.style.display = 'none'
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(url)
}

/**
 * 将文件url转成blob对象。
 * @param { String } url - https://api/file/20240906.docx
 * @returns 返回Blob对象
 */
export async function fileUrl2Blob(url: string): Promise<Blob> {
  return await new Promise((resolve, reject) => {
    const xml = new XMLHttpRequest()
    xml.open('GET', url, true)
    xml.responseType = 'blob'
    xml.onreadystatechange = function () {
      if (xml.readyState === 4) {
        if (xml.status === 200) {
          resolve(new Blob([xml.response]))
        } else {
          reject(new Error(`Failed to load file, status: ${xml.status}`))
        }
      }
    }
    xml.send()
  })
}
